package edu.zcmu.seckill.service.impl;


import edu.zcmu.seckill.entity.SeckillOrder;
import edu.zcmu.seckill.enumeration.GlobalEnum;
import edu.zcmu.seckill.enumeration.OrderStatusEnum;
import edu.zcmu.seckill.service.SeckillOrderService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    SeckillOrderService seckillOrderService;
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        String[] split = expiredKey.split(":");
        if (split.length>=6&&GlobalEnum.USER_SECKILL_PRODUCT_IS_EXPIRATION.getCode().equals(split[0]+":"+split[1]+":"+split[2]+":")){
            redisTemplate.delete(GlobalEnum.USER_SECKILL_PRODUCT_IS.getCode()+split[3]+":"+split[4]);
            SeckillOrder seckillOrder = new SeckillOrder();
            seckillOrder.setOrderId(split[5]);
            seckillOrder.setUserId(Integer.valueOf(split[3]));
            seckillOrder.setSeckillId(Integer.valueOf(split[4]));
            seckillOrder.setOrderStatus(OrderStatusEnum.ORDER_OVERDUE.getCode());
            seckillOrderService.updateSeckillOrder(seckillOrder);
            RSemaphore semaphore = redissonClient
                    .getSemaphore(GlobalEnum.GET_SECKILL_PRODUCT_COUNT_REDIS.getCode() + split[4]);
            semaphore.release();

        }


    }
}
